package com.jqsoft.launcher.activity.gairui;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.jqsoft.launcher.R;
import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.PersonnelInformation;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.activity.fragment.EcgResultViewerFragment;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.ToastUtil;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * Created by Administrator on 2017-12-05.
 * 显示心电波形图的activity
 */

public class EcgResultViewerActivity extends JQActivity {
    private final String tag = "EcgResultViewerActivity";
    private PersonnelInformation personInfo;
    private String content;
    private Thread thread;

    private EcgResultViewerFragment viewerFragment;

    private boolean isDestroyed=false;

    public EcgResultViewerActivity() {
        super();
    }

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_ecg_result_viewer);

        setGoBackListener();
        initPersonInfo();

        loadInfo();
    }

    private void showWaitEcgPlayerHint(){
        ToastUtil.showToast(this, "请等待心电图播放完毕");
    }

    @Override
    public void onBackPressed() {
        boolean canGoBack = canEcgPlayingEnd();
        Log.d("chenxu", "canGoBack is "+canGoBack);
        if (!canGoBack){
            showWaitEcgPlayerHint();
            return;
        }

        stopThread();
        super.onBackPressed();
    }

    private void setGoBackListener(){
        Button title_bar_left_button=(Button) findViewById(R.id.title_bar_left_button);
        title_bar_left_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean canGoBack = canEcgPlayingEnd();
                Log.d("chenxu", "canGoBack is "+canGoBack);
                if (!canGoBack){
                    showWaitEcgPlayerHint();
                    return;
                }
                stopThread();
                act.finish();
                overridePendingTransition(android.R.anim.slide_in_left,
                        android.R.anim.slide_out_right);

            }
        });

    }

    private void showFragment(final Bundle bundle){
        if (!isDestroyed) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
                    FragmentManager manager = getFragmentManager();
                    FragmentTransaction transaction = manager.beginTransaction();
                    viewerFragment = new EcgResultViewerFragment();
                    viewerFragment.setArguments(bundle);
                    transaction.replace(R.id.fl, viewerFragment);
                    transaction.commit();

//                }
//            });
        }


    }

    private boolean canEcgPlayingEnd(){
        if (viewerFragment==null){
            return true;
        } else {
            return viewerFragment.canEcgPlayEnd;
        }
    }

    private String getArchiveNo(){
        if (personInfo!=null){
            return personInfo.getsNo();
        } else {
            return "";
        }
    }

    private String getPersonName(){
        if (personInfo!=null){
            return personInfo.getsPersonName();
        } else {
            return "";
        }
    }

    private String getCardNo(){
        if (personInfo!=null){
            return personInfo.getsCardNo();
        } else {
            return "";
        }
    }

    private Handler myhandler = new Handler() {
        public void handleMessage(Message msg) {
            if (isDestroyed){
                return;
            }
            switch (msg.what) {
                case Constant.MSG_LOAD_OVER:
                    dismissrogressBar();
                    JSONObject o = (JSONObject) msg.obj;
                    Bundle bundle = getFragmentBundleFromParameters(o);
                    showFragment(bundle);

                    break;
                case Constant.MSG_LOAD_ERROR:
                    dismissrogressBar();
                    MessageTools.showDialogOkBack(act, "获取此人心电检测记录失败！");
                    break;
                case Constant.MSG_LOAD_ZARO:
                    dismissrogressBar();
                    MessageTools.showDialogOkBack(act, "获取此人心电检测记录失败！");
                    break;
                case Constant.MSG_LOAD_EMPTY:
                    dismissrogressBar();
                    MessageTools.showDialogOkBack(act, "此人暂无心电检测记录！");
                    break;
                default:
                    break;
            }
        }
    };


    private Runnable sendable = new Runnable() {
        @Override
        public void run() {
            String methodName = BphsURL.getCommonPath("XINDIAN_ECG_GET_ONE_DATA_METHOD");
            //BphsURL.getCommonPath("GetPersonInfoByECG_METHOD");
            String requestUrl = BphsURL.getCommonPath("XINDIANECGWebService_URL");
            // String requestUrl =
            // "http://60.171.146.122:9098/WebService/Andrews/PsychosisPersonWebService.asmx";
            Log.i(tag, "查询:content" + requestUrl);
            // String methodName="GetPsychosisPersonManageData";
            JSONObject data = new JSONObject();
            // {"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
            try {
                UserLoginInfo info = UserLoginInfo.getInstances();
                data.put("sAreaCode", info.getsManagementDivisionCode());//
//                if (jiciNum != 0) {
//                    data.put("iCurrentPageIndex", (jiciNum * 10 + 1) + "");
//                } else {
                    data.put("iCurrentPageIndex", "1");
//                }
                data.put("iPageSize", "1"); //
                data.put("sNo", getArchiveNo()); //
                data.put("sPersonName", getPersonName()); //
                data.put("sCardNo", getCardNo()); //
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            content = WebServiceUtils.requestByParams(methodName,
                    data.toString(), requestUrl);
            if (StringUtils.isNotBlank(content)) {
                try {
                    Log.i(tag, "返回的查询结果" + content);
                    // String result= content.replaceAll("\\\\", "");
                    // Log.i(tag, "返回的查询结果"+result);
                    JSONObject json = new JSONObject(content);
                    // Log.i(tag, "返回的查询结果"+result);"AllCount":0,
                    JSONObject jo = new JSONObject(json.getString("Data"));
                    JSONArray jsonArray = (JSONArray) jo.get("Table");
                    if (jsonArray==null || jsonArray.length() == 0){
                        myhandler.sendEmptyMessage(Constant.MSG_LOAD_EMPTY);
                    } else {
                        JSONObject o = (JSONObject) jsonArray.get(0);
//                        Bundle bundle = getFragmentBundleFromParameters(o);
//                        showFragment(bundle);
                        Message msg = myhandler.obtainMessage(Constant.MSG_LOAD_OVER, o);
                        myhandler.sendMessage(msg);
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    myhandler.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
                }
            } else {
                //返回字符串为空
                myhandler.sendEmptyMessage(Constant.MSG_LOAD_ZARO);
            }
        }
    };

    private Bundle getFragmentBundleFromParameters(JSONObject o){
        Bundle bundle=new Bundle();
        if (o == null){
            return bundle;
        }
        String sNo = o.optString("sNo", "");
        String sPersonName = o.optString("sPersonName", "");
        String sCardNo = o.optString("sCardNo", "");
        String sECGData = o.optString("sECGData", "");
        String sECGResult = o.optString("sECGResult", "");
        String hp = o.optString("hp", "");
        String lp = o.optString("lp", "");
        String notch = o.optString("notch", "");
        String hr = o.optString("hr", "");
        String pAxis = o.optString("pAxis", "");
        String qrsAxis = o.optString("qrsAxis", "");
        String taxis = o.optString("taxis", "");
        String prInterval = o.optString("prInterval", "");
        String qrsDuration = o.optString("qrsDuration", "");
        String qtd = o.optString("qtd", "");
        String qtc = o.optString("qtc", "");
        String rv5 = o.optString("rv5", "");
        String sv1 = o.optString("sv1", "");
        String rv5sv1 = o.optString("rv5sv1", "");
        String pWidth = o.optString("pWidth", "");
        String pExist = o.optString("pExist", "");
        String inputer = o.optString("inputer", "");
        String inputCode = o.optString("inputCode", "");
        String sInputDeptCode = o.optString("sInputDeptCode", "");
        String sInputDeptName = o.optString("sInputDeptName", "");
        String sAreaCode = o.optString("sAreaCode", "");
        String dAddTime = o.optString("dAddTime", "");
        String sDoctorName = o.optString("sDoctorName", "");
        String sPersonID = o.optString("sPersonID", "");
        String inputDate = o.optString("inputDate", "");
        String resultCodes = o.optString("resultCodes", "");
        String And_xueya = o.optString("And_xueya", "");
        String And_xinlv = o.optString("And_xinlv", "");
        String And_xuetang = o.optString("And_xuetang", "");
        String And_xuehongdanbai = o.optString("And_xuehongdanbai", "");
        String And_tiwen = o.optString("And_tiwen", "");
        String And_mailv = o.optString("And_mailv", "");
        String And_huxipinlv = o.optString("And_huxipinlv", "");
        String And_xindian = o.optString("And_xindian", "");
        int IsService = o.optInt("IsService", -1);

        bundle.putString("hp", hp);
        bundle.putString("lp", lp);
        bundle.putString("notch", notch);
        bundle.putString("hr", hr);
        bundle.putString("pWidth", pWidth);
        bundle.putString("qrs", qrsDuration);
        bundle.putString("rv5", rv5);
        bundle.putString("sv1", sv1);
        bundle.putString("pr", prInterval);
        bundle.putString("rv5sv1", rv5sv1);
        bundle.putString("qtd", qtd);
        bundle.putString("qtc", qtc);
        bundle.putString("pAxis", pAxis);
        bundle.putString("qrsAxis", qrsAxis);
        bundle.putString("tAxis", taxis);
        bundle.putString("sECGResult", sECGResult);
        bundle.putString("sECGData", sECGData);
        return bundle;
    }

    private void stopThread(){
        try {
//            myhandler.removeCallbacksAndMessages(null);
            if (thread!=null && thread.isAlive()){
                thread.interrupt();
            }
            thread = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadInfo(){
        loadWaitPanel();
        stopThread();
        thread = new Thread(sendable);
        thread.start();
    }

    private void initPersonInfo(){
        Intent intent = getIntent();
        if (intent!=null){
            personInfo = (PersonnelInformation) intent.getSerializableExtra("personInfo");
        }
    }



    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);  //不保存fragment的状态
        stopThread();
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_ecg_result_viewer;
    }

    @Override
    protected void initGui() {

    }

    @Override
    protected void initAction() {
        setGoBack();

    }

    @Override
    protected void initData() {
        setTitle("心电检测波形图");

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestroyed=true;
    }
}
